<!--
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-25 10:32:32
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-05-25 13:19:23
 * @FilePath: \iam-ui\iam-ui\src\components\echarts\pie2.vue
 * @Description: 文件介绍
 * 
 * Copyright (c) 2025 by user.email, All Rights Reserved. 
-->

<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
    <div class="count-display">{{ count }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

// 定义 props，外部可传入 value（当前值）、total（总值）、color（主色）
const props = defineProps({
  color: {
    type: Array,
    default: () => [
      "#2396eb",
      "#4ecb73",
      "#fbd437",
      "#f04864",
      "#975fe5",
      "#36cbcb",
      "#f759ab",
    ],
  },
  value: {
    type: Number,
    required: true,
  },
  total: {
    type: Number,
    default: 100,
  },
  color: {
    type: String,
    default: "#09f",
  },
  count: {
    type: Number,
    default: 0,
  },
});

const chartRef = ref(null);
let chartInstance = null;

const renderChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  const percent = Math.max(0, Math.min(props.value / props.total, 1));
  chartInstance.setOption({
    color: props.color,
    series: [
      {
        type: "pie",
        radius: ["60%", "80%"],
        avoidLabelOverlap: false,
        silent: true,
        label: { show: false },
        data: [
          {
            value: percent,
            name: "进度",
            itemStyle: { color: props.color },
          },
          {
            value: 1 - percent,
            name: "剩余",
            itemStyle: { color: "#eee" },
          },
        ],
      },
    ],
  });
  chartInstance.resize(); // 渲染后自适应一次
};
// 新增 resize 方法
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
onMounted(() => {
  renderChart();
  window.addEventListener("resize", handleResize);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
watch(
  () => [props.value, props.total, props.color],
  () => {
    renderChart();
  }
);
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.chart {
  width: 100%;
  height: 100%;
}

.count-display {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  font-weight: bold;
  color: #333;
  opacity: 0;
  transition: opacity 0.3s ease;
  /* background-color: rgba(255, 255, 255, 0.9); */
  padding: 4px 8px;
  border-radius: 4px;
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.chart-container:hover .count-display {
  opacity: 1;
}
</style>
